import Ipha_ComponentBasic from "./Ipha_ComponentBasic";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu("ipha组件/简单晃动动画")
export default class Ipha_SwayAni extends Ipha_ComponentBasic {

    comName: string = "晃动动画";

    @property({ displayName: "会缩放" })
    private m_IsScale: boolean = true;

    @property({ displayName: "缩放幅度", visible() { return this.m_IsScale; } })
    private m_ScaleScope: number = 0.1;

    @property({ displayName: "缩放用时", visible() { return this.m_IsScale; } })
    private m_ScaleTime: number = 0.1;

    @property({ displayName: "晃动幅度" })
    private m_SwayScope: number = 20;

    @property({ displayName: "单次晃动用时" })
    private m_SwayOnceTime: number = 0.05;

    @property({ displayName: "晃动次数", tooltip: "左右一组算一次" })
    private m_SwayCnt: number = 2;

    @property({ displayName: "动画重播延迟" })
    private m_Delay: number = 1;

    @property({ displayName: "自动播放" })
    private m_IsAuto: boolean = true;

    @property({ displayName: "循环播放" })
    private m_IsLoop: boolean = true;

    private m_NodeAngle: number = 0;
    private m_NodeScale: number = 1;

    onLoad() {
        this.m_NodeAngle = this.node.angle;
        this.m_NodeScale = this.node.scale;
    }

    start() {
        if (this.m_IsAuto) {
            this.playAni();
        }
    }

    playAni() {
        let tween = this.getTweenAni();
        if (this.m_IsLoop) {
            tween = tween.repeatForever();
        }
        tween.start();
    }

    stopAni() {
        cc.Tween.stopAllByTarget(this.node);
        this.node.scale = this.m_NodeScale;
        this.node.angle = this.m_NodeAngle;
    }

    private getTweenAni() {
        let tween: cc.Tween<cc.Node> = cc.tween(this.node);
        const nodeScale = this.node.scale;
        if (this.m_IsScale) {
            tween = tween.to(this.m_ScaleTime, { scale: this.m_ScaleScope + nodeScale });
        }

        tween = tween
            .by(this.m_SwayOnceTime, { angle: this.m_SwayScope })
            .by(this.m_SwayOnceTime, { angle: -this.m_SwayScope * 2 });

        for (let i = 0; i < this.m_SwayCnt - 1; i++) {
            tween = tween
                .by(this.m_SwayOnceTime, { angle: this.m_SwayScope * 2 })
                .by(this.m_SwayOnceTime, { angle: -this.m_SwayScope * 2 });
        }

        tween = tween.to(this.m_SwayOnceTime / 2, { angle: this.m_NodeAngle });

        if (this.m_IsScale) {
            tween = tween.to(this.m_ScaleTime, { scale: this.m_NodeScale });
        }

        tween = tween
            .delay(this.m_Delay)
            .union();

        return tween;
    }

    // update (dt) {}
}
